package com.jack.leetcode.eachproblem_2020;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhang_j on 2020/11/4
 */
public class 插入区间 {

    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> list = new ArrayList<>();
        if(intervals == null || intervals.length == 0){
            list.add(newInterval);
        }else{
            int n = intervals.length;
            int i = 0;
            while(i < n && intervals[i][1] < newInterval[0]){
                list.add(intervals[i]);
                i++;
            }
            while(i < n && intervals[i][0] <= newInterval[1]){
                newInterval[0] = Math.min(intervals[i][0], newInterval[0]);
                newInterval[1] = Math.max(intervals[i][1], newInterval[1]);
                i++;
            }
            list.add(newInterval);
            while(i < n){
                list.add(intervals[i]);
                i++;
            }
        }
        int[][] result = new int[list.size()][2];
        for(int i = 0;i < list.size();i++){
            result[i] = list.get(i);
        }
        return result;
    }
}
